package com.neusoft.EYSystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neusoft.EYSystem.dao.BedDAO;
import com.neusoft.EYSystem.dao.BedUsageDAO;
import com.neusoft.EYSystem.dao.ClientDAO;
import com.neusoft.EYSystem.po.*;
import com.neusoft.EYSystem.service.BedUsageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class BedUsageServiceImpl implements BedUsageService {
    @Autowired
    private BedUsageDAO bedUsageDAO;

    @Autowired
    private ClientDAO clientDAO;

    @Autowired
    private BedDAO bedDAO;

    @Override
    public PageResponseBean<List<ClientBedUsage>> bedUsagePage(String name, String checkinDateStart, String checkinDateEnd, String status, Long page, Long size) {
        QueryWrapper<Client> clientQueryWrapper = new QueryWrapper<>();
        if (name != null && !name.isEmpty()) {
            clientQueryWrapper.like("name", name);
        } else {
            clientQueryWrapper.isNotNull("name"); // 如果没有提供名字，则查询所有客户
        }

        List<Integer> clientIds = clientDAO.selectList(clientQueryWrapper)
                .stream()
                .map(Client::getClientId)
                .toList();

        if (clientIds.isEmpty()) {
            return new PageResponseBean<>(500, "没有找到符合条件的客户");
        }

        QueryWrapper<BedUsage> bedUsageQueryWrapper = new QueryWrapper<>();
        bedUsageQueryWrapper.in("client_id", clientIds);
        if (status != null && !status.isEmpty()) {
            bedUsageQueryWrapper.eq("status", status);
        }

        // 时间处理
        if (checkinDateStart != null && !checkinDateStart.isEmpty() && checkinDateEnd != null && !checkinDateEnd.isEmpty()) {
            bedUsageQueryWrapper.between("start_date", checkinDateStart, checkinDateEnd);
        } else if (checkinDateStart != null && !checkinDateStart.isEmpty()) {
            bedUsageQueryWrapper.ge("start_date", checkinDateStart);
        } else if (checkinDateEnd != null && !checkinDateEnd.isEmpty()) {
            bedUsageQueryWrapper.le("start_date", checkinDateEnd);
        }

        bedUsageQueryWrapper.orderByDesc("end_date");

        IPage<BedUsage> bedUsageIPage = new Page<>(page, size);
        IPage<BedUsage> bedUsages = bedUsageDAO.selectPage(bedUsageIPage, bedUsageQueryWrapper);

        Set<Integer> resultsClientIds = bedUsages.getRecords()
                .stream()
                .map(BedUsage::getClientId)
                .collect(Collectors.toSet());
        Map<Integer,Client> clientMap = new HashMap<>();

        if (!resultsClientIds.isEmpty()) {
            QueryWrapper<Client> clientQuery = new QueryWrapper<>();
            clientQuery.in("client_id", resultsClientIds);
            List<Client> clients = clientDAO.selectList(clientQuery);
            clientMap = clients.stream()
                    .collect(Collectors.toMap(Client::getClientId, client -> client));
        }else{
            return new PageResponseBean<>(500, "没有找到符合条件的客户");
        }

        List<ClientBedUsage> results = new ArrayList<>();
        for (BedUsage bedUsage : bedUsages.getRecords()) {
            ClientBedUsage clientBedUsage = new ClientBedUsage();
            clientBedUsage.setBedUsage(bedUsage);
            clientBedUsage.setClient(clientMap.get(bedUsage.getClientId()));
            results.add(clientBedUsage);
        }

        PageResponseBean<List<ClientBedUsage>> responseBean = new PageResponseBean<>();
        responseBean.setData(results);
        responseBean.setTotal(bedUsages.getTotal());
        responseBean.setStatus(200);
        responseBean.setMsg("床位使用情况查询成功");
        return responseBean;
    }

    @Transactional
    @Override
    public ResponseBean<Integer> exchangeBed(BedUsage bedUsage) {
        Bed bed = bedDAO.selectById(bedUsage.getBedId());
        bedUsage = bedUsageDAO.selectById(bedUsage.getUsageId());
        LocalDateTime now = LocalDateTime.now();
        String endDateStr = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String edn = bedUsage.getEndDate();
        bedUsage.setEndDate(endDateStr);
        bedUsage.setStatus("已结束");

        int updateResult = bedUsageDAO.updateById(bedUsage);
        if (updateResult > 0) {
            // 更新床位状态为已使用
            bed.setStatus("occupied");
            int bedUpdateResult = bedUsageDAO.updateById(bedUsage);
            if (bedUpdateResult > 0) {
                int bedId = bedUsage.getBedId();
                Client client = clientDAO.selectById(bedUsage.getClientId());
                Bed obed = bedDAO.selectById(bedId);
                if(obed == null) {
                    return new ResponseBean<>(404, "床位不存在");
                }else{
                    obed.setStatus("free");
                    bedDAO.updateById(obed);
                    client.setBedId(bed.getBedId());
                    clientDAO.updateById(client);

                    BedUsage bu = new BedUsage();
                    bu.setClientId(bedUsage.getClientId());
                    bu.setBedId(bed.getBedId());
                    bu.setStartDate(endDateStr);
                    bu.setEndDate(edn);
                    bu.setStatus("使用中");

                    bed.setStatus("occupied");

                    if(bedUsageDAO.insert(bu) > 0 && bedDAO.updateById(bed) > 0) {
                        return new ResponseBean<>(200, "床位交换成功", bedId);
                    } else {
                        return new ResponseBean<>(500, "床位使用记录插入失败");
                    }
                }
            } else {
                return new ResponseBean<>(500, "床位状态更新失败");
            }
        } else {
            return new ResponseBean<>(404, "床位使用记录不存在或更新失败");
        }
    }
}
